<template>
  <div class="addBrand-container">
    <div class="container">
      <el-form ref="ruleForm"
               :model="ruleForm"
               :rules="rules"
               :inline="true"
               label-width="180px"
               class="demo-ruleForm">
        <div>
          <el-form-item label="学号:" prop="sno">
            <el-input 
              v-model.number="ruleForm.sno"
              type="number"
              placeholder="请填写学生学号"
              maxlength="14"
              @input="handleSnoInput"
            />
          </el-form-item>
          <el-form-item label="学生姓名:" prop="name">
            <el-input v-model="ruleForm.name"
                      placeholder="请填写学生名称"
                      maxlength="14" />
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="ruleForm.sex">
              <el-radio label="男">男</el-radio>
              <el-radio label="女">女</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="年龄:" prop="age">
            <el-input 
              v-model.number="ruleForm.age"
              type="number"
              placeholder="请填写学生年龄"
              maxlength="14"
              @input="handleSnoInput"
            />
          </el-form-item>
          <el-form-item label="学生图片:" required prop="image">
            <image-upload :prop-image-url="imageUrl"
                          @imageChange="imageChange">
              图片大小不超过2M<br>仅能上传 PNG JPEG JPG类型图片<br>建议上传200*200或300*300尺寸的图片
            </image-upload>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="学生所属班级:" required prop="classId">
            <el-select v-model="ruleForm.classId" 
                       placeholder="请选择所属班级"
                       clearable
                       filterable
                       @change="handleCollegeChange">
              <el-option 
                v-for="college in classList"
                :key="college.id"
                :label="college.name"
                :value="college.id"
              />
            </el-select>
          </el-form-item>
        </div>
        <div class="address">
          <el-form-item label="学生描述:">
            <el-input v-model="ruleForm.description"
                      type="textarea"
                      :rows="3"
                      maxlength="200"
                      placeholder="学生描述，最长200字" />
          </el-form-item>
        </div>
        <div class="subBox address">
          <el-form-item>
            <el-button @click="() => $router.back()">
              取消
            </el-button>
            <el-button type="primary"
                       :class="{ continue: actionType === 'add' }"
                       @click="submitForm('ruleForm', false)">
              保存
            </el-button>
            <el-button v-if="actionType === 'add'"
                       type="primary"
                       @click="submitForm('ruleForm', true)">
              保存并继续添加
            </el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import HeadLable from '@/components/HeadLable/index.vue'
import ImageUpload from '@/components/ImgUpload/index.vue'
import { addStudent, findStudentById, updateStudent } from '@/api/student'
import { getClass } from '@/api/class' 
import { FormInstance } from 'element-ui/types/form'

interface Class {
  id: number;
  name: string;
}

interface StudentForm {
  sno: string | null;
  name: string;
  image: string;
  classId: number | null;
  age: number | null;
  sex: string;
  description: string;
  id?: string;
}

@Component({
  name: 'AddStudent',
  components: {
    HeadLable,
    ImageUpload
  }
})
export default class extends Vue {
  private value: string = '';
  private seachKey: string = '';
  private dishList: any[] = [];
  private imageUrl: string = '';
  private actionType: string = 'add';
  private dishTable: any[] = [];
  private dialogVisible: boolean = false;
  private checkList: any[] = [];
  private classList: Class[] = [];
  
  private ruleForm: StudentForm = {
    sno: null,
    name: '',
    classId: null,
    age: null,
    sex: '',
    image: '',
    description: ''
  };

  get rules() {
    return {
      sno: {
        required: true,
        message: '学生学号不能为空',
        trigger: ['blur', 'change'],
        validator: (rule: any, value: number | null, callback: Function) => {
          if (!value) {
            callback(new Error('学生学号不能为空'));
          } else if (typeof value !== 'number' || isNaN(value)) {
            callback(new Error('学号必须是数字'));
          } else {
            callback();
          }
        }
      },age: {
        required: true,
        message: '学生年龄不能为空',
        trigger: ['blur', 'change'],
        validator: (rule: any, value: number | null, callback: Function) => {
          if (!value) {
            callback(new Error('学生年龄不能为空'));
          } else if (typeof value !== 'number' || isNaN(value)) {
            callback(new Error('年龄必须是数字'));
          } else {
            callback();
          }
        }
      },
      name: {
        required: true,
        validator: (rule: any, value: string, callback: Function) => {
          if (!value) {
            callback(new Error('请输入学生名称'));
          } else if (!/^([A-Za-z0-9\u4e00-\u9fa5]){2,20}$/.test(value)) {
            callback(new Error('学生名称需2-20个字符（汉字、字母、数字）'));
          } else {
            callback();
          }
        },
        trigger: 'blur'
      },
      image: {
        required: true,
        message: '学生图片不能为空',
        trigger: 'blur'
      },
      classId: {
        required: true,
        message: '请选择班级',
        trigger: 'change'
      },
      sex: {
        required: true,
        message: '请选择学生性别',
        trigger: 'change'
      }
    };
  }

  async created() {
    await this.fetchCollegeList();
    
    this.actionType = this.$route.query.id ? 'update' : 'add';
    if (this.actionType === 'update') {
      const id = this.$route.query.id as string;
      if (id) {
        findStudentById(Number(id))
          .then(res => {
            if (res.data.code === 1) {
              this.ruleForm = res.data.data;
              this.imageUrl = this.ruleForm.image;
              
              if (this.ruleForm.classId && !this.classList.some(c => c.id === this.ruleForm.classId)) {
                console.warn(`班级ID ${this.ruleForm.classId} 不在班级列表中`);
              }
            } else {
              this.$message.error(res.data.message);
              this.$router.push('/student');
            }
          })
          .catch(error => {
            console.error('获取学生信息失败:', error);
            this.$message.error('获取学生信息失败，请重试');
            this.$router.push('/student');
          });
      } else {
        this.$message.error('缺少学生ID');
        this.$router.push('/student');
      }
    }
  }

  // 获取班级列表
  private async fetchCollegeList() {
    try {
      const params = { page: 1, pageSize: 1000 };
      const response = await getClass(params);
      
      if (response.data.code === 1) {
        this.classList = response.data.data.records || [];
        
        if (this.classList.length === 0) {
          this.$message.warning('班级列表为空，请先添加班级');
        }
      } else {
        this.$message.error(response.data.message || '获取班级列表失败');
      }
    } catch (error) {
      console.error('获取班级列表失败:', error);
      this.$message.error('获取班级列表失败，请重试');
    }
  }

  // 处理学号输入，过滤非数字字符
  private handleSnoInput(event: Event) {
    const input = event.target as HTMLInputElement;
    input.value = input.value.replace(/[^\d]/g, '');
    this.ruleForm.sno = input.value ? input.value : null;
  }

  // 班级选择变化处理
  private handleCollegeChange(classId: number) {
    console.log('选择的班级ID:', classId);
    this.$forceUpdate();
  }

  $refs: {
    ruleForm: FormInstance;
  }

  public submitForm(formName: string, isContinue: boolean): void {
    this.$refs[formName].validate((valid: boolean) => {
      if (valid) {
        if (this.actionType === 'add') {
          addStudent(this.ruleForm)
            .then(res => {
              if (res.data.code === 1) {
                this.$message.success('学生添加成功!');
                if (isContinue) {
                  this.ruleForm = {
                    sno: null,
                    name: '',
                    image: '',
                    age: null,
                    sex: '',
                    classId: null,
                    description: ''
                  };
                  this.imageUrl = '';
                } else {
                  this.$router.push('/student');
                }
              } else {
                this.$message.error(res.data.message);
              }
            })
            .catch(error => {
              console.error('添加学生失败:', error);
              this.$message.error('添加学生失败，请重试');
            });
        } else {
          updateStudent(this.ruleForm)
            .then(res => {
              if (res.data.code === 1) {
                this.$message.success('学生修改成功!');
                this.$router.push('/student');
              } else {
                this.$message.error(res.data.message);
              }
            })
            .catch(error => {
              console.error('更新学生失败:', error);
              this.$message.error('更新学生失败，请重试');
            });
        }
      }
    });
  }

  public imageChange(value: string): void {
    this.ruleForm.image = value;
    this.imageUrl = value;
  }

  private handleClose(): void {
    this.dialogVisible = false;
  }

  private addTableList(): void {
    this.dialogVisible = false;
  }

  private getCheckList(list: any[]): void {
    this.checkList = list;
  }
}
</script>

<style>
.avatar-uploader .el-icon-plus:after {
  position: absolute;
  display: inline-block;
  content: ' ' !important;
  left: calc(50% - 20px);
  top: calc(50% - 40px);
  width: 40px;
  height: 40px;
  background: url('./../../assets/icons/icon_upload@2x.png') center center no-repeat;
  background-size: 20px;
}
</style>

<style lang="scss">
.addBrand-container {
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #ffc200;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 200px;
    height: 160px;
    line-height: 160px;
    text-align: center;
  }

  .avatar {
    width: 200px;
    height: 160px;
    display: block;
  }

  .el-input {
    width: 293px;
  }

  .address {
    .el-form-item__content {
      width: 777px !important;
    }
  }

  .el-input__prefix {
    top: 2px;
  }

  .addDish {
    .el-input {
      width: 130px;
    }

    .el-input-number__increase {
      border-left: solid 1px #fbe396;
      background: #fffbf0;
    }

    .el-input-number__decrease {
      border-right: solid 1px #fbe396;
      background: #fffbf0;
    }

    input {
      border: 1px solid #fbe396;
    }

    .table {
      border: solid 1px #ebeef5;
      border-radius: 3px;

      th {
        padding: 5px 0;
      }

      td {
        padding: 7px 0;
      }
    }
  }

  .addDishList {
    .seachDish {
      position: absolute;
      top: 12px;
      right: 20px;
    }

    .el-dialog__footer {
      padding-top: 27px;
    }

    .el-dialog__body {
      padding: 0;
      border-bottom: solid 1px #efefef;
    }

    .seachDish {
      .el-input__inner {
        height: 40px;
        line-height: 40px;
      }
    }
  }
}
</style>

<style lang="scss" scoped>
.addBrand {
  &-container {
    margin: 30px;

    .container {
      position: relative;
      z-index: 1;
      background: #fff;
      padding: 30px;
      border-radius: 4px;
      min-height: 500px;

      .subBox {
        padding-top: 30px;
        text-align: center;
        border-top: solid 1px $gray-5;
      }

      .addDish {
        width: 777px;

        .addBut {
          background: #ffc200;
          display: inline-block;
          padding: 0px 20px;
          border-radius: 3px;
          line-height: 40px;
          cursor: pointer;
          border-radius: 4px;
          color: #333333;
          font-weight: 500;
        }

        .content {
          background: #fafafb;
          padding: 20px;
          border: solid 1px #d8dde3;
          border-radius: 3px;
        }
      }
    }
  }
}
</style>